package org.chen.learn.demo.utils;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

/**
 * JGit工具类
 *
 * @author chensj
 * @date 2020-03-31 12:34
 */
public class GitUtils {

    /**
     * 获取凭证
     *
     * @param username 用户名
     * @param password 密码
     * @return 凭证
     */
    public static CredentialsProvider credentialsProvider(String username, String password) {
        return new UsernamePasswordCredentialsProvider(username, password);
    }

    /**
     * clone远程仓库
     *
     * @param repo     仓库地址
     * @param local    本地存放路径
     * @param provider 凭证
     * @return git
     */
    public static Git cloneRepository(String repo, String local, CredentialsProvider provider) throws GitAPIException {
        Git git = Git.cloneRepository()
                .setCredentialsProvider(provider)
                .setURI(repo)
                .setDirectory(new File(local)).call();
        return git;
    }

    /**
     * 读取已有仓库
     * @param dir 仓库所在位置
     * @return 仓库
     * @throws IOException
     */
    public static Repository getRepositoryFromDir(String dir) throws IOException {
        return new FileRepositoryBuilder()
                .setGitDir(Paths.get(dir, ".git").toFile())
                .build();
    }

    /**
     * commit 提交代码
     *
     * @param git      git类
     * @param message  提交说明
     * @param provider 凭证
     */
    public static void commitRepository(Git git, String message, CredentialsProvider provider) throws GitAPIException {
        git.add().addFilepattern(".").call();
        git.commit().setMessage(message).call();
    }

    /**
     * git 推送
     * @param git git 客户端
     * @param provider 凭证
     * @throws GitAPIException
     * @throws IOException
     */
    public static void push(Git git, CredentialsProvider provider) throws GitAPIException, IOException {
        push(git,null,provider);
    }

    /**
     * git 推送
     * @param git git 客户端
     * @param branch 分支
     * @param provider 凭证
     * @throws GitAPIException
     * @throws IOException
     */
    public static void push(Git git, String branch, CredentialsProvider provider) throws GitAPIException, IOException {
        if (branch == null) {
            branch = git.getRepository().getBranch();
        }
        git.push()
                .setCredentialsProvider(provider)
                .setRemote("origin").setRefSpecs(new RefSpec(branch)).call();
    }
}
